<?php
/**
 * 文章 
 * @好商城b1 (c) 2005-2016 33hao Inc.
 * @license    http://www.33hao.com
 * @link       交流群号：216611541
 * @since      好商城提供技术支持 授权请购买shopnc授权
 * 
 **/

defined('In33hao') or exit('Access Invalid!');
class articleControl extends mobileHomeControl{
    //文章评论类型
    const ARTICLE = 1;
    const PICTURE = 2;
	public function __construct() {
        parent::__construct();
    }

    /**
     * 文章列表
     */
    public function article_listOp() {
        if(!empty($_GET['ac_id']) && intval($_GET['ac_id']) > 0) {
			$article_class_model	= Model('article_class');
			$article_model	= Model('article');
			$condition	= array();
			
			$child_class_list = $article_class_model->getChildClass(intval($_GET['ac_id']));
			$ac_ids	= array();
			if(!empty($child_class_list) && is_array($child_class_list)){
				foreach ($child_class_list as $v){
					$ac_ids[]	= $v['ac_id'];
				}
			}
			$ac_ids	= implode(',',$ac_ids);
			$condition['ac_ids']	= $ac_ids;
			$condition['article_show']	= '1';
			$article_list = $article_model->getList($condition);
			$article_type_name = $this->article_type_name($ac_ids);
			output_data(array('article_list' => $article_list, 'article_type_name'=> $article_type_name));		
		}
		else {
			output_error('缺少参数:文章类别编号');
		}    	
    }

    /**
     * 根据类别编号获取文章类别信息
     */
    private function article_type_name() {
    	if(!empty($_GET['ac_id']) && intval($_GET['ac_id']) > 0) {
			$article_class_model = Model('article_class');
			$article_class = $article_class_model->getOneClass(intval($_GET['ac_id']));
			return ($article_class['ac_name']);
		}
		else {
			return ('缺少参数:文章类别编号');			
		}    	
    }

    /**
     * 根据姓氏查找文章
     */
    public function articleByFirstnameOp(){
        $key = $_POST['word'];
        if($key){
            $condition['firstname'] = $key;
        }
        $article_model = Model('cms_article');
        $result = $article_model->getArcticleList($condition,$_GET['page']);
        foreach ($result as $k => $value){
            //转化图片路径格式
            $result[$k]['ImageUrl'] = getCMSArticleImageUrl($value['article_attachment_path'],$value['article_image'],'list');
            //转化时间格式
            $result[$k]['date']=date('Y-m-d',$result[$k]['article_publish_time']);
        }
        if($result){
            $res = ['status'=>200,'msg'=>'ok','data'=>$result];
            echo json_encode($res);
            exit();
        }

        $res = ['status'=>200,'msg'=>'数据为空'];
        echo json_encode($res);
        exit();
    }

    /**
     * 单篇文章显示
     */
    public function article_showOp() {
		$article_model	= Model('article');

        if(!empty($_GET['article_id']) && intval($_GET['article_id']) > 0) {
			$article	= $article_model->getOneArticle(intval($_GET['article_id']));

			if (empty($article)) {
				output_error('文章不存在');
			}
			else {
				output_data($article);
			}
        } 
        else {
			output_error('缺少参数:文章编号');
        }
    }

    public function indexOp()
    {
        $shuju = $_POST;
        $article_model = Model('cms_article');
        if ($shuju['member_provinceid']) {
            $conditin['province_id'] = $shuju['member_provinceid'];
        }
        if ($shuju['member_cityid']) {
            $conditin['city_id'] = $shuju['member_cityid'];
        }
        if ($shuju['member_areaid']) {
            $conditin['area_id'] = $shuju['member_areaid'];
        }
        $conditin['article_class_id'] = 1;
        $result = $article_model->getArcticleList($conditin,$_GET['page']);
        foreach ($result as $k => $value){
            //转化图片路径格式
            $result[$k]['ImageUrl'] = getCMSArticleImageUrl($value['article_attachment_path'],$value['article_image'],'list');
            //转化时间格式
            $result[$k]['date']=date('Y-m-d',$result[$k]['article_publish_time']);
        }
            if($result){
             $res = ['status'=>200,'msg'=>'ok','data'=>$result];
             echo json_encode($res);
             exit();
        }

        $res = ['status'=>200,'msg'=>'数据为空'];
        echo json_encode($res);
        exit();

    }

    /**
     * 咨询详情页
     */
    public function article_detailOp(){
        $article_model	= Model('cms_article');
        $data = array();
        if(!empty($_GET['article_id']) && intval($_GET['article_id']) > 0) {
          $data['article']	= $article_model->getArticle(intval($_GET['article_id']));
                //转化时间格式
                $data['article']['date']=date('Y-m-d',  $data['article']['article_publish_time']);
            if (empty($data['article'])) {
                output_error('文章不存在');
            }
            else {
                output_data($data);
            }
            //评论查询
            $cms_comment=Model('cms_comment');
            $comment=$cms_comment->getList(intval($_GET['article_id']));
            if(empty($comment)){
                output_data('评论不存在！');
            }else{
                output_data($comment);
            }



        }
        else {
            output_error('缺少参数:文章编号');
        }
    }
    /**
     * 姓氏列表页
     */
    public function indexNameListOp()
    {
        //接收数据
        $shuju=$_POST;
        //实例化对象
        $model=Model('cms_article');
        $key = 'article_nameList';
        //是否存在关键值
        if ($_POST['keyword']) {
            if (preg_match("/^[a-zA-Z]+$/", $_POST['keyword'])) {
                $conditin['abbreviate'] = $shuju['keyword'];
            } else {
                $conditin['firstname'] = $shuju['keyword'];
            }
        }
        if(rkcache($key)){
              // 缓存源数据
              $result = rkcache($key);
              if($conditin) {
                   $_tempres = [];
                  if ($conditin['abbreviate']){
                      $key = strtoupper($conditin['abbreviate']);
                      if(array_key_exists($key,$result['list'])){
                          $_tempres[$key] = $result['list'][$key];
                      }else{
                          $_tempres = [];
                      }
                      $result['list'] = $_tempres;
                  }
                  if ($conditin['firstname']){
                      $_tempres = [];
                      $key = $conditin['firstname'];
                      foreach ($result['list'] as $k => $item){
                           foreach ($item as $ke => $value){
                                  if($value==$key){
                                         $_tempres[$k][] = $value;
                                  }
                           }
                      }
                      $result['list']  = $_tempres;
                  }
              }

        }else {
            $result['list'] = $model->getGroupList($conditin);
            //去除重复元素
            foreach ($result['list'] as $k => $v) {
                $result['list'][$k] = array_unique($v);
            }
            wkcache($key,$result);
        }
            if($result){
                $res=['status'=>200,'msg'=>'ok','data'=>$result];
                //数据json数据
                echo json_encode($res);
                exit();
            }
    }

    /**
     * 评论保存
     **/
    public function comment_saveOp() {
        $member_id =  $this->getMemberIdIfExists();
        if(empty($_SESSION['member_id'])){
               $_SESSION['is_login'] = 1;
               $_SESSION['member_id'] = $member_id;
        }
        $member_info = Model('member')->getMemberInfo(array('member_id'=>$member_id));
        $data = array();
        $data['result'] = 'true';
        $comment_object_id = intval($_GET['comment_object_id']);
        $comment_type = $_GET['comment_type'];
        $model_name = '';
        $count_field = '';
        switch ($comment_type) {
            case 'article':
                $comment_type = self::ARTICLE;
                $model_name = 'cms_article';
                $count_field = 'article_comment_count';
                $comment_object_key = 'article_id';
                break;
            case 'picture':
                $comment_type = self::PICTURE;
                $model_name = 'cms_picture';
                $count_field = 'picture_comment_count';
                $comment_object_key = 'picture_id';
                break;
            default:
                $comment_type = 0;
                break;
        }

        if($comment_object_id <= 0 || empty($comment_type) || empty($_GET['comment_message'])) {
            $data['result'] = 'false';
            $data['message'] = "参数错误";
            self::echo_json($data);
        }

        if(!empty($_SESSION['member_id'])) {

            $param = array();
            $param['comment_type'] = $comment_type;
            $param["comment_object_id"] = $comment_object_id;
            if (strtoupper(CHARSET) == 'GBK'){
                $param['comment_message'] = Language::getGBK(trim($_GET['comment_message']));
            } else {
                $param['comment_message'] = trim($_GET['comment_message']);
            }
            $param['comment_member_id'] = $member_info['member_id'];
            $param['comment_time'] = time();

            $model_comment = Model('cms_comment');

            if(!empty($_POST['comment_id'])) {
                $comment_detail = $model_comment->getOne(array('comment_id'=>$_GET['comment_id']));
                if(empty($comment_detail['comment_quote'])) {
                    $param['comment_quote'] = $_GET['comment_id'];
                } else {
                    $param['comment_quote'] = $comment_detail['comment_quote'].','.$_GET['comment_id'];
                }
            } else {
                $param['comment_quote'] = '';
            }

            $result = $model_comment->save($param);
            if($result) {

                //评论计数加1
                $model = Model($model_name);
                $update = array();
                $update[$count_field] = array('exp',$count_field.'+1');
                $condition = array();
                $condition[$comment_object_key] = $comment_object_id;
                $model->modify($update, $condition);

                //返回信息
                $data['result'] = 'true';
                $data['message'] = Language::get('nc_common_save_succ');
                $data['member_name'] = $member_info['member_name'];
                $data['member_avatar'] = getMemberAvatar($member_info['avatar']);
                $data['member_link'] = SITEURL.DS.'index.php?act=member_snshome&mid='.$_SESSION['member_id'];
                $data['comment_message'] = parsesmiles(stripslashes($param['comment_message']));
                $data['comment_time'] = date('Y-m-d H:i:s',$param['comment_time']);
                $data['comment_id'] = $result;

            } else {
                $data['result'] = 'false';
                $data['message'] = Language::get('nc_common_save_fail');
            }
        } else {
            $data['result'] = 'false';
            $data['message'] = Language::get('no_login');
        }
        self::echo_json($data);
    }

    protected function echo_json($data) {
        if (strtoupper(CHARSET) == 'GBK'){
            $data = Language::getUTF8($data);//网站GBK使用编码时,转换为UTF-8,防止json输出汉字问题
        }
        echo json_encode($data);die;
    }

    // 获取分类信息
    public function articleTypeOp(){
        $type = $_POST['type'];
        $memberId = $this->getMemberIdIfExists();
        // 查询登录的信息
        $where['member_id'] = $memberId;
        $memberInfo = Model('member')->getMemberInfo($where);
        $cms_class_model = Model('cms_article_class');
        $class = $cms_class_model->getOne(array('class_id'=>$type));
        $data['member'] = $memberInfo;
        $data['class'] = $class;
        output_data(array('data'=>$data));
    }

    // 发布文章
    public function article_addOp(){
        if(empty($_POST['title'])) {
            $res = ['status'=>400,'msg'=>"标题不能为空"];
            output_data($res);
        }
        //插入文章
        $param = array();
        $param['article_title'] = trim($_POST['title']);
        $class = intval($_POST['article_class']);
        if(empty($_POST['article_title_short'])) {
            $param['article_title_short'] = mb_substr($_POST['article_title'], 0, 12, CHARSET);
        } else {
            $param['article_title_short'] = $_POST['article_title_short'];
        }
        $param['article_class_id'] = $class;
        $param['article_origin'] = trim($_POST['article_origin']);
        $param['article_origin_address'] = trim($_POST['article_origin_address']);
        $param['article_author'] = trim($_POST['article_author']);
        $param['article_abstract'] = mb_substr(trim($_POST['article_abstract']), 0, 140, CHARSET);
        $param['article_content'] = trim($_POST['article_content']);
        $param['article_link'] = trim($_POST['article_link']);
        $param['article_keyword'] = trim($_POST['article_keyword']);
        $param['article_comment_count'] = empty($_POST['article_comment_count'])?0:intval($_POST['article_comment_count']);
        $param['article_click'] = empty($_POST['article_click'])?0:intval($_POST['article_click']);
        ;
        $param['article_keyword'] = trim($_POST['article_keyword']);
        if(empty($_POST['article_id'])) {
            $param['article_publisher_name'] = $this->publisher_name;
            $param['article_publisher_id'] = $this->publisher_id;
            $param['article_type'] = $this->publisher_type;
            $param['article_attachment_path'] = $this->attachment_path;
            $param['article_sort'] = 255;
        }
        $param['article_commend_flag'] = 0;
        $param['article_tag'] = trim($_POST['article_tag']);
        if($class==1){
            $param['province_id'] = $_POST['province_id'];
            $param['city_id'] = $_POST['city_id'];
            $param['area_id'] = $_POST['area_id'];
            $param['address_info'] = $_POST['region'];
        }else{
            $param['firstname'] = $_POST['firstname'];
            $param['abbreviate'] = strtoupper($_POST['abbreviate']);
        }
        // 图片上传
        if ($_POST['thumb']) {
            $res = $this->upImgs($_POST['thumb'], BASE_UPLOAD_PATH.DS.ATTACH_CMS.DS.'article'.$this->attachment_path);
        }
        $imagePath = [];
        if ($res) {
            foreach ($res as $v) {
                $imagefix = substr($v,strripos($v,'.'));
                $imagePath[]=  basename($v).",";
                $imagepix = substr($v,0,strripos($v,'.'));
                // 目标图路径
                $whidth = 250;
                $heigth = 250;
                $dis_path = $imagepix."_list".$imagefix;
                $res = $this->resize($v,$dis_path,$whidth,$heigth); // 生成缩略图
            }
        }
        //文章图片
        if($imagePath) {
            $article_image_all = array();
            foreach ($imagePath as $value) {
                list($file_name, $file_path) = explode(',', $value);
                $file_path = empty($file_path)?$this->attachment_path:$file_path;
                $article_image_url = getCMSArticleImageUrl($file_path, $file_name, 'list');
                list($width, $height, $type, $attr) = getimagesize($article_image_url);
                $article_image_all[$file_name]['name'] = $file_name;
                $article_image_all[$file_name]['width'] = $width;
                $article_image_all[$file_name]['height'] = $height;
                $article_image_all[$file_name]['path'] = $file_path;
            }
            $param['article_image_all'] = serialize($article_image_all);
        }
        $article_image = trim($imagePath[0],',');
        if(!empty($article_image)) {
            $param['article_image'] = serialize($article_image_all[$article_image]);
        }

        //文章商品
        if(!empty($_POST['article_goods_url'])) {
            $article_goods_list = array();
            for ($i = 0,$count = count($_POST['article_goods_url']); $i < $count; $i++) {
                $article_goods = array();
                $article_goods['url'] = $_POST['article_goods_url'][$i];
                $article_goods['title'] = $_POST['article_goods_title'][$i];
                $article_goods['image'] = $_POST['article_goods_image'][$i];
                $article_goods['price'] = $_POST['article_goods_price'][$i];
                $article_goods['type'] = $_POST['article_goods_type'][$i];
                $article_goods_list[] = $article_goods;
            }

            if(!empty($article_goods_list)) {
                $param['article_goods'] = serialize($article_goods_list);
            } else {
                $param['article_goods'] = '';
            }
        }

        //发布时间
        if(!empty($_POST['article_publish_time'])) {
            $param['article_publish_time'] = strtotime($_POST['article_publish_time']);
        } else {
            $param['article_publish_time'] = time();
        }
        $param['article_modify_time'] = time();

        if($_POST['save_type'] == 'publish') {
            $param['article_state'] = $this->publish_state;
        } else {
            $param['article_state'] = self::ARTICLE_STATE_DRAFT;
        }

        $model_article = Model('cms_article');
        $model_tag_relation = Model('cms_tag_relation');
        if(!empty($_POST['article_id'])) {
            $article_id = intval($_POST['article_id']);
            $article_auth = $this->check_article_auth($article_id);
            if($article_auth) {
                $model_article->modify($param,array('article_id'=>$article_id));
                $model_tag_relation->drop(array('relation_type'=>1,'relation_object_id'=>$article_id));
            } else {
                showMessage(Language::get('wrong_argument'),'','','error');
            }
        } else {
            $article_id = $model_article->save($param);
        }
        //插入文章标签
        if(!empty($_POST['article_tag'])) {
            $tag_list = explode(',', $_POST['article_tag']);
            $param = array();
            $param['relation_type'] = 1;
            $param['relation_object_id'] = $article_id;
            $params = array();
            foreach ($tag_list as $value) {
                $param['relation_tag_id'] = $value;
                $params[] = $param;
            }
            $model_tag_relation->saveAll($params);
        }
        dkcache('article_nameList');
        if($article_id) {
            $res = ['status'=>200,'msg'=>"文章保存成功"];
            output_data($res);
        } else {
            $res = ['status'=>400,'msg'=>"文章保存失败"];
            output_data($res);
        }

    }

    protected function check_article_auth($article_id) {
        if($article_id > 0) {
            $model_article = Model('cms_article');
            $article_detail = $model_article->getOne(array('article_id'=>$article_id));
            if(!empty($article_detail)) {
                if($article_detail['article_publisher_id'] == $this->publisher_id) {
                    return $article_detail;
                }
            }
        }
        return FALSE;
    }

    /**
     *上传多图  仅限 base64
     * @param $imgs
     * @param bool|false $dir 路径
     * @param bool|true $isdel
     * @return string
     */
    public function upImgs($imgs, $dir = false)
    {
        $dir = $dir ? $dir : date('Ymd');
        $res = '';
        foreach ($imgs as $k => $v) {
            if (file_exists($v)) {
                $res[$k] = $v;
            } else {
                $v = explode(',', $v);
                $imgpath = $dir . "/";
                preg_match('/image\/(.*);base64/u', $v[0], $imgtype);
                $imgtype = $imgtype[1] == "jpeg" ? 'jpg' : $imgtype[1];
                if (!file_exists($imgpath)) {
                    mkdir($imgpath);
                }
                list($usec, $sec) = explode(" ", microtime());
                $imgname = $sec . str_replace('0.', '_', $usec);
                $imgname = $imgname . '.' . $imgtype;
                $base64 = base64_decode(end($v));
                $save = file_put_contents($imgpath . $imgname, $base64);
                if ($save) {
                    $res[$k] = $imgpath . $imgname;
                }
            }
        }
        return $res;
    }
}
